package com.mrjy.maintain.bo;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.mrjy.common.dto.SMSSendDto;
import com.mrjy.common.entity.SMSSendInfo;
import com.mrjy.common.entity.SMSSendReqInfo;
import com.mrjy.common.util.RandomUtil;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.common.util.SMSTemplate;
import com.mrjy.common.util.SMSUtil;
import com.mrjy.maintain.dao.ISMSSendInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;

@Service("smsSendInfoBo")
public class SMSSendInfoBo implements ISMSSendInfoBo {
	@Resource
	private ISMSSendInfoDao smsSendInfoDao;
	@Resource
	private IUserInfoDao userInfoDao;

	@Override
	public int sendSMS(SMSSendDto smsSendDto) {
		int result = 0;
		String uniqueFlag = "";
		if (smsSendDto.getUniqueFlag() != null) {
			uniqueFlag = smsSendDto.getUniqueFlag();
		}
		String smsType = "normal";
		String smsFreeSignName = SMSUtil.SIGN_NAME[0];
		SMSTemplate sms = SMSTemplate.TEMPLATE_01;
		switch (smsSendDto.getTypeId()) {
		case 1:
			sms = SMSTemplate.TEMPLATE_01;
			break;
		case 2:
			sms = SMSTemplate.TEMPLATE_02;
			break;
		case 7:
			sms = SMSTemplate.TEMPLATE_07;
			break;
		case 8:
			sms = SMSTemplate.TEMPLATE_08;
			break;
		case 9:
			sms = SMSTemplate.TEMPLATE_09;
			break;
		case 10:
			sms = SMSTemplate.TEMPLATE_10;
			break;
		case 11:
			sms = SMSTemplate.TEMPLATE_11;
			break;
		case 12:
			sms = SMSTemplate.TEMPLATE_12;
			break;
	
		}
		Map<String, Object> smsParamMap = new HashMap<String, Object>();
		String sendCode = RandomUtil.generateString2(6);
		smsParamMap.put("code", sendCode);
		if (smsSendDto.getProduct() != null) {
			smsParamMap.put("product",smsSendDto.getProduct());
		}
		if (smsSendDto.getPrice() != null) {
			smsParamMap.put("price", smsSendDto.getPrice());
		}
		if (smsSendDto.getPayment() != null) {
			smsParamMap.put("payment",smsSendDto.getPayment());
		}
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo(smsType,
				smsFreeSignName, smsParamMap, smsSendDto.getRecNum(), sms);

		Map<String, Object> map = SMSUtil.sendSMS(smsSendReq);
		if (map.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
			// 将未使用的信息记录标记为已失效
			SMSSendInfo smsSendInfo = new SMSSendInfo(); 
			smsSendInfo.setSmsStatus("2");
			smsSendInfo.setSmsCode(sms.getTemplateID());
			smsSendInfo.setRecNum(smsSendDto.getRecNum());
			smsSendInfoDao.updateStatusSelective(smsSendInfo);

			// 插入一条信息记录
			JSONObject jsonObject = JSONObject.fromObject(map
					.get("responseDesc"));
			jsonObject = JSONObject.fromObject(jsonObject
					.getString("alibaba_aliqin_fc_sms_num_send_response"));
			jsonObject = JSONObject.fromObject(jsonObject.getString("result"));						
			smsSendInfo.setSendCode(sendCode);
			smsSendInfo.setUniqueFlag(uniqueFlag);		
			smsSendInfo.setSmsSendTime(new Date());
			smsSendInfo.setSmsStatus("0");
			smsSendInfo.setBizCode(jsonObject.getString("model"));
			result = smsSendInfoDao.insert(smsSendInfo);
			
			/*System.out.println(jsonObject.getString("model"));// 打印短信发送流水
			result = insertSMSInfo(jsonObject.getString("model"),
					smsSendDto.getRecNum(), sendCode, uniqueFlag);*/
		}

		return result;
	}



	@Override
	public SMSSendInfo validateSMSCode(SMSSendInfo smsSendInfo) {
		//changeErrorCode(smsSendInfo);
		smsSendInfo.setSmsCode(SMSTemplate.getTemplateID(smsSendInfo.getTypeId()));
		SMSSendInfo smsSendInfoDB = smsSendInfoDao.validateSMSCode(smsSendInfo);
		if (smsSendInfoDB == null) {
			smsSendInfoDB = new SMSSendInfo();
			smsSendInfoDB.setSmsMessage("codeError");
		} else if (smsSendInfoDB.getSmsSendTime().getTime() + 600000 < new Date()
				.getTime()) {
			smsSendInfoDB.setSmsMessage("timeOut");
		}else {
			//smsSendInfo.setSmsStatus("2");
			//smsSendInfoDao.updateStatusSelective(smsSendInfo);
			smsSendInfoDB.setSmsMessage("ok");
		}
		return smsSendInfoDB;
	}

	/**
	 * 发送短信
	 * @param recNum 手机号码
	 * @param smsParamMap 模板参数值
	 * @param smsTemp 模板类型
	 * @param smsStatus 消息状态（ 0：未使用，1：已使用，2：已失效      通知型传2）
	 * @param smsType 消息类型（0：通知型；1：验证型   传null时为通知型）
	 * @return
	 */
	@Override
	public Object sendSMSAndAddRecord(String recNum ,Map<String,Object> smsParamMap 
			,SMSTemplate smsTemp,String smsStatus,String smsType){
		Map<String , Object> map = new HashMap<String , Object>();
		if(StringUtils.isBlank(recNum)){
			map.put("err_code", 100);
			map.put("err_msg", "手机号码为空");
			return map;
		}
		if(smsTemp == null){
			map.put("err_code", 101);
			map.put("err_msg", "模板消息为空");
			return map;
		}
		if(smsParamMap == null){
			map.put("err_code", 102);
			map.put("err_msg", "消息参数为空");
			return map;
		}
		//设置验证码
		String sendCode = "";
		if("1".equals(smsType)){
			sendCode = RandomUtil.generateString2(6);
			smsParamMap.put("code", sendCode);
		}
		
		SMSSendReqInfo smsSendReq = new SMSSendReqInfo("normal",SMSUtil.SIGN_NAME[0]
				,smsParamMap,recNum,smsTemp);
		
		try {
			Map<String,Object> respMap = SMSUtil.sendSMS(smsSendReq);
			if (respMap.get("responseCode") == ResponseCode.SUCCESS.getCode()) {
				JSONObject  jsonObject = JSONObject.fromObject(respMap.get("responseDesc"));				
				jsonObject = JSONObject.fromObject(jsonObject.getString("alibaba_aliqin_fc_sms_num_send_response"));
				jsonObject = JSONObject.fromObject(jsonObject.getString("result"));
				
				SMSSendInfo smsSendInfo = new SMSSendInfo(); 
				if("1".equals(smsType)){
					// 将未使用的信息记录标记为已失效
					smsSendInfo.setSmsStatus("2");
					smsSendInfo.setSmsCode(smsTemp.getTemplateID());
					smsSendInfo.setRecNum(recNum);
					smsSendInfoDao.updateStatusSelective(smsSendInfo);
					//新增的记录为0
					smsSendInfo.setSmsStatus("0");
					smsSendInfo.setSendCode(sendCode);
				}else{
					smsSendInfo.setSmsStatus("2");
				}
				
				smsSendInfo.setSmsCode(smsTemp.getTemplateID());
				smsSendInfo.setRecNum(recNum);
				smsSendInfo.setSmsSendTime(new Date());		
				smsSendInfo.setBizCode(jsonObject.getString("model"));
				smsSendInfoDao.insert(smsSendInfo);
				
				map.put("err_code", 200);
				map.put("err_msg", "发送成功");
			} else {
				map.put("err_code", respMap.get("responseCode"));
				map.put("err_msg", respMap.get("responseDesc"));
			}									
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return map;
	}
}
